package fr.vahren.dotastrat.model;

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import fr.vahren.dotastrat.game.D2SGame;
import fr.vahren.dotastrat.game.D2SGameState;
import fr.vahren.dotastrat.game.D2SMessage;

public class D2SPlayer {

	private List<D2SHeroUnit> controlledUnits;
	private D2SSide side;

	private boolean hasStarted = false;

	private boolean hasEnded = false;

	private int id;

	public D2SPlayer(D2SSide side) {
		controlledUnits = new ArrayList<D2SHeroUnit>();
		this.side = side;

		this.id = D2SGame.id();

	}

	public List<D2SHeroUnit> getControlledUnits() {
		return controlledUnits;
	}

	public void setControlledUnits(List<D2SHeroUnit> controlledUnits) {
		this.controlledUnits = controlledUnits;
	}

	public void addControlledUnit(D2SHeroUnit hero) {
		controlledUnits.add(hero);
	}

	/**
	 * @return the side
	 */
	public D2SSide getSide() {
		return side;
	}

	/**
	 * @param side
	 *            the side to set
	 */
	public void setSide(D2SSide side) {
		this.side = side;
	}

	/**
	 * @return the hasStarted
	 */
	public boolean isHasStarted() {
		return hasStarted;
	}

	/**
	 * @param hasStarted
	 *            the hasStarted to set
	 */
	public void setHasStarted(boolean hasStarted) {
		this.hasStarted = hasStarted;
	}

	/**
	 * @return the hasEnded
	 */
	public boolean isHasEnded() {
		return hasEnded;
	}

	/**
	 * @param hasEnded
	 *            the hasEnded to set
	 */
	public void setHasEnded(boolean hasEnded) {
		this.hasEnded = hasEnded;
	}

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	public D2SHeroUnit getUnit(int heroId) {
		for (D2SHeroUnit unit : controlledUnits) {
			if (unit.getId() == heroId) {
				return unit;
			}
		}
		return null;
	}

	public JSONObject generateInfo(D2SGameState phase, List<D2SMessage> msgs) {
		JSONObject p = new JSONObject();

		p.put("id", id);
		p.put("side", side.toString());

		JSONArray units = new JSONArray();
		for (D2SHeroUnit unit : controlledUnits) {
			units.add(unit.generateInfo(phase));
		}
		p.put("units", units);
		
		// messages
		JSONArray messages = new JSONArray();
		for(D2SMessage m:msgs){
			messages.add(m.generateInfo());
		}
		p.put("messages", messages);

		return p;
	}

}
